package com.iflytek.jzcpx.procuracy.web.cont.controller;

import java.util.List;

import com.alibaba.csb.sdk.ContentBody;
import com.alibaba.csb.sdk.HttpCaller;
import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iflytek.jzcpx.procuracy.common.model.HandContResult;
import com.iflytek.jzcpx.procuracy.cont.model.ArchiveCatalogueResultDto;
import com.iflytek.jzcpx.procuracy.cont.model.JZML;
import com.iflytek.jzcpx.procuracy.cont.model.JZMLWJ;
import com.iflytek.jzcpx.procuracy.cont.model.SuccessJsonResult;
import com.iflytek.jzcpx.procuracy.cont.service.ContService;
import com.iflytek.jzcpx.procuracy.cont.vo.HandContModel;
import com.iflytek.jzcpx.procuracy.web.config.MetricInterface;
import com.iflytek.jzcpx.procuracy.web.cont.bd.ContBDService;
import com.iflytek.jzcpx.procuracy.web.cont.dto.ContModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 自动编目 接口
 *
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2019-08-06 19:52
 */
@Api(value = "自动编目", tags = "自动编目")
@RestController
@RequestMapping("/cont")

// @Api("数据中台电子卷宗对接")
// @RequestMapping(value = "/dzjz", produces = "application/json")
public class ContController {

    private static final Logger logger = LoggerFactory.getLogger(ContController.class);

    @Autowired
    private ContService contService;

    @Autowired
    private ContBDService contBDService;

    // @Value("${ali.ak}")
    // private String ak;

    // @Value("${ali.sk}")
    // private String sk;

    // @Value("${ali.requestURL}")
    // private String requestURL;

    // @Value("${ali.dzjzmlwj}")
    // private String dzjzmlwj;

    // @Value("${ali.bczdjz}")
    // private String bczdjz;

    // @Value("${ali.version}")
    // private String version;

    // @Value("${ali.znbm.version}")
    // private String znbmVersion;

    /**
     * 接收数据中台提交编目请求
     */
    @ApiOperation(value = "接收数据中台提交编目请求", notes = "接收数据中台提交编目请求")
    @RequestMapping(value = {"/acceptCatalogueRequest"}, method = RequestMethod.POST)
    @MetricInterface(stringVal = "接收数据中台提交编目请求")
    public SuccessJsonResult<Void> acceptCatalogueRequest(@RequestBody ContModel jo) throws Exception {

        String dzjzmlwj = "";// 电子卷宗目录文件
        String version = "";
        String bczdjz = "";//
        String znbmVersion = "";// 智能编目版本

        //logger.info(String.format("传入参数:%s", param));
        //JSONObject jo = JSONObject.parseObject(param);
        String bsbh = jo.getBsbh();
        logger.info(String.format("请求获取电子卷宗案件目录文件信息,传入参数:%s", jo.toString()));

        // v1.0逻辑，不要删除
        // String result = doPostForDZJZ(dzjzmlwj, jo.toString(), version);

        String result = contService.getDZJZInfo(bsbh);
        logger.info(String.format("请求获取电子卷宗案件目录文件信息,返回数据:%s", result));
        JSONObject jsonObject = JSONObject.parseObject(result);

        if (jsonObject == null) {
            //获取目录文件失败
            logger.info("获取目录文件失败");
            return null;
        }
        String jzml = "";
        String jzmlwj = "";
        if (jsonObject.getString("code").equals("0")) {
            String data = jsonObject.getString("data");
            JSONObject json = JSONObject.parseObject(data);
            jzml = json.getString("jzml");
            jzmlwj = json.getString("jzmlwj");
        }
        JSONArray jajzml = JSONArray.parseArray(jzml);
        JSONArray jajzmlwj = JSONArray.parseArray(jzmlwj);

        List<JZML> mlList = null;
        if (jajzml != null) {
            mlList = JSONObject.parseArray(jajzml.toJSONString(), JZML.class);
        }

        List<JZMLWJ> wjList = JSONObject.parseArray(jajzmlwj.toJSONString(), JZMLWJ.class);

        // 获取ocr文件识别结果路径
        contBDService.matchResult(wjList, bsbh);

        // 提交编目结果到电子卷宗系统.
        ArchiveCatalogueResultDto dto = contBDService.ocrAndContFile(mlList, wjList, bsbh,null);
        dto.setBSBH(bsbh);
        //dto.setBMSAH(bsbh);
        logger.info(String.format("保存电子卷宗传入参数:%s", JSONObject.toJSONString(dto)));
        //String resultSave = doPostForDZJZ(bczdjz, JSONObject.toJSONString(dto), znbmVersion);
        String resultSave = contService.saveDzjzzzInfo(JSONObject.toJSONString(dto));
        logger.info(String.format("保存电子卷宗返回参数:%s", resultSave));
        return new SuccessJsonResult<>();
    }

    /**
     * 手动编目
     *
     * @param handContModel
     * @return
     */
    @ApiOperation(value = "手动触发编目", notes = "接收用户点击编目请求")
    @RequestMapping(value = {"/hand/cont"},method = RequestMethod.GET)
    @MetricInterface(stringVal = "手动触发编目")
    public HandContResult handCont(@RequestParam String jzbh, @RequestParam String mlbh) {
	logger.info("手动触发编目开始，参数 jzbh:{},mlbh:{}",jzbh,mlbh);
        try {
            HandContModel handContModel=new HandContModel();
            handContModel.setJzbh(jzbh);
            handContModel.setMlbh(mlbh);
            return contBDService.handCont(handContModel);
        }
        catch (Throwable e) {
            logger.warn("手动触发编目异常", e);
        }
        HandContResult handContResult = new HandContResult();
        handContResult.setCode("500");
        handContResult.setMessage("智能编目服务异常");
        handContResult.setSuccess(false);
        return handContResult;
    }

    /**
     * @param apiName
     * @param param
     * @param version
     * @return
     */
    private String doPostForDZJZ(String apiName, String param, String version) {
        String result = "";
        String ak = "";
        String sk = "";
        String requestURL = "";
        try {
            result = HttpCaller.doPost(requestURL, apiName, version, new ContentBody(param), ak, sk);
            logger.info(String.format("电子卷宗返回结果:%s", result));
        } catch (HttpCallerException e) {
            e.printStackTrace();
            logger.error("请求电子卷宗失败!", e);
        }

        return result;
    }
}
